package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websock.WebSocketServer;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 老杨
 * @version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    AddressBookMapper addressBookMapper;

    @Autowired
    ShoppingCartMapper shoppingCartMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    WeChatPayUtil weChatPayUtil;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WebSocketServer webSocketServer;

    @Override
    public OrderSubmitVO orderSubmit(OrdersSubmitDTO ordersSubmitDTO) {
        //基础校验
        //1.校验 地址是否存在
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //2.校验 购物车 是否为null
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(userId).build();
        List<ShoppingCart> list = shoppingCartMapper.select(shoppingCart);
        if (list == null || list.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //插入 订单表
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        //完善 数据
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());

        orderMapper.insert(orders);

        //插入订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (ShoppingCart shoppingCart1 : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart1, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        //批量 插入
        orderDetailMapper.inserts(orderDetails);

        //插入后 ，删除对应用户购物车的数据
        shoppingCartMapper.delete2(userId);

        //封装vo 数据
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime()).build();


        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    @Override
    public void paySuccess(String outTradeNo) {
        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);
        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间

        //TODO
        //报错 ，但是可以正常编译 启动项目
//        Orders build = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now()).build();


    }

    @Override
    public PageResult page(int page, int pageSize, Integer status) {
        //设置分页
        PageHelper.startPage(page, pageSize);
        //拿到 用户id
        Long userId = BaseContext.getCurrentId();
        //查询 订单
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setStatus(status);
        ordersPageQueryDTO.setUserId(userId);
        Page<Orders> orders = orderMapper.page(ordersPageQueryDTO);
        List<OrderVO> orderVOList = new ArrayList<>();
        //根据 订单id 查询 订单详情
        for (Orders orders1 : orders) {
            List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders1.getId());
            OrderVO orderVO = new OrderVO();
            //封装 成 vo，一个vo 就是 一个订单
            BeanUtils.copyProperties(orders1, orderVO);
            orderVO.setOrderDetailList(orderDetailList);
            orderVOList.add(orderVO);
        }
        //封装 成 pageResult
        return new PageResult(orders.getTotal(), orderVOList);
    }

    @Override
    public OrderVO orderDetail(Long id) {
        //拿到订单
        Orders orders = orderMapper.getByOrdersId(id);
        OrderVO orderVO = new OrderVO();
        //拷贝到 vo
        BeanUtils.copyProperties(orders, orderVO);
        //获取订单对应的 订单详情
        List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(id);
        //在把订单详情封装到 vo
        orderVO.setOrderDetailList(orderDetails);

        //返回 vo
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }

    /**
     * 再来一单的意思 是 将相同菜品和套餐 再次放到购物车中
     * 而不是 直接生成订单
     *
     * @param id
     */
    @Override
    public void repetitionOrder(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单id查询当前订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        // 将订单详情对象转换为购物车对象
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x -> {
            ShoppingCart shoppingCart = new ShoppingCart();

            // 将原订单详情里面的菜品信息重新复制到购物车对象中
            BeanUtils.copyProperties(x, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            return shoppingCart;
        }).collect(Collectors.toList());

        // 将购物车对象批量添加到数据库
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //获取订单
        Page<Orders> page = orderMapper.page(ordersPageQueryDTO);
//        封装到 vo
        List<OrderVO> orderVOList = new ArrayList<>();
        for (Orders orders : page) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(orders, orderVO);
            //订单详情封装
            List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orders.getId());
            orderVO.setOrderDetailList(orderDetails);
            //把一个订单 的订单详情 的所有菜品信息 封装到 字符串中
            StringBuilder dishName = new StringBuilder(); //把菜品名字 拼接到一起
            for (OrderDetail orderDetail : orderDetails) {
                String name = orderDetail.getName();
                Integer number = orderDetail.getNumber();
                dishName.append(name + "*" + number + ";");
            }
            orderVO.setOrderDishes(dishName.toString());
            orderVOList.add(orderVO);
        }


        //最后封装到 pageResult
        return new PageResult(page.getTotal(), orderVOList);
    }

    @Override
    public OrderStatisticsVO statistics() {
//         2待接单 3已接单 4派送中
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        Integer statistics = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer statistics2 = orderMapper.statistics(Orders.CONFIRMED);
        Integer statistics3 = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);

        orderStatisticsVO.setToBeConfirmed(statistics);
        orderStatisticsVO.setConfirmed(statistics2);
        orderStatisticsVO.setDeliveryInProgress(statistics3);

        return orderStatisticsVO;
    }

    @Override
    public void payment2(OrdersPaymentDTO ordersPaymentDTO) {
        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        orders.setCheckoutTime(LocalDateTime.now());
        orderMapper.update(orders);

        //在支付完之后，往管理端 发送 json 格式的来电提醒
//        这里 定好规范 1 是来单   2 是催单
        Map map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号 ：" +orders.getNumber());

        String json = JSON.toJSONString(map);
        //发送到管理端
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public void confirm(Long id) {
        Orders orders = orderMapper.getByOrdersId(id);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO rejectionDTO) {

        Orders orders = orderMapper.getByOrdersId(rejectionDTO.getId());
        //拒单
//        检查订单状态，和支付状态，已支付下需要退款
//       .......


//         1.填入拒单原因
        orders.setRejectionReason(rejectionDTO.getRejectionReason());
//          2.修改 订单状态
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
//        3.更新到数据库中
        orderMapper.update(orders);

    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders = orderMapper.getByOrdersId(ordersCancelDTO.getId());


        Orders orders1 = new Orders();
        //取消订单
        //        检查订单状态，和支付状态，已支付下需要退款
//       .......


//         1.填入取消原因
        orders1.setCancelReason(ordersCancelDTO.getCancelReason());
//          2.修改 订单状态
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelTime(LocalDateTime.now());
        orders1.setId(ordersCancelDTO.getId());

//        3.更新到数据库中
        orderMapper.update(orders1);
    }

    @Override
    public void delivery(Long id) {
        //修改一下订单状态即可
        Orders orders = orderMapper.getByOrdersId(id);
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        // 根据id查询订单
        Orders ordersDB = orderMapper.getByOrdersId(id);

        // 校验订单是否存在，并且状态为4
        if (ordersDB == null || !ordersDB.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders orders = new Orders();
        orders.setId(ordersDB.getId());
        // 更新订单状态,状态转为完成
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders orders = orderMapper.getByOrdersId(id);
        if (orders == null) {
          throw new OrderBusinessException("订单为 null");
        }
        Map map = new HashMap();
        map.put("type", 2);
        map.put("orderId", orders.getId());
        map.put("content", "订单号 ：" +orders.getNumber());

        String json = JSON.toJSONString(map);
        //发送到管理端
        webSocketServer.sendToAllClient(json);

    }


}
